<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
        <el-card class="box-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>能源监控指标</span>
            </div>
          </template>
          <div class="energy-stats">
            <div class="stat-item">
              <div class="stat-value">{{ deviceCount }}</div>
              <div class="stat-label">设备总数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ totalEnergy }}</div>
              <div class="stat-label">总能耗(kWh)</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ todayReportCount }}</div>
              <div class="stat-label">今日上报数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ warningCount + dangerCount }}</div>
              <div class="stat-label">异常数据</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
        <el-card class="box-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>WebSocket连接状态</span>
            </div>
          </template>
          <div class="connection-status">
            <el-alert
              :title="webSocketConnected ? 'WebSocket已连接' : 'WebSocket未连接'"
              :type="webSocketConnected ? 'success' : 'error'"
              :closable="false"
              show-icon
            >
              <p>创建能源报告数据时将通过WebSocket接收提醒</p>
              <p v-if="webSocketConnected">消息将以弹窗形式显示</p>
              <p v-else>请检查网络连接或刷新页面</p>
            </el-alert>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-4">
      <el-col :span="24">
        <el-card class="box-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近报告数据</span>
              <el-button type="primary" link @click="refreshLatestReports">刷新</el-button>
            </div>
          </template>
          <div v-loading="latestReportsLoading">
            <el-table :data="latestReports" stripe>
              <el-table-column label="设备名称" min-width="150">
                <template #default="{ row }">
                  {{ getDeviceName(row.deviceId) }}
                </template>
              </el-table-column>
              <el-table-column label="设备ID" prop="deviceId" min-width="120" />
              <el-table-column label="上报数据类型" prop="reportDataType" min-width="120">
                <template #default="{ row }">
                  {{ getReportTypeLabel(row.reportDataType) }}
                </template>
              </el-table-column>
              <el-table-column label="上报数据实际值" prop="reportDataValue" min-width="120" />
              <el-table-column label="上报数据级别" min-width="120">
                <template #default="{ row }">
                  <el-tag :type="getReportLevelType(row.reportDataLevel)">
                    {{ getReportLevelLabel(row.reportDataLevel) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                label="上报时间"
                prop="reportDataTime"
                min-width="160"
                :formatter="dateFormatter"
              />
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { dateFormatter } from '@/utils/formatTime'
import { getRefreshToken } from '@/utils/auth'
import * as ReportApi from '@/api/energy/report'
import * as DeviceApi from '@/api/energy/device'
import { DeviceVO } from '@/api/energy/device'
import { reportDataTypeOptions, reportDataLevelOptions } from '@/api/energy/report'

// 统计数据
const deviceCount = ref(0)
const totalEnergy = ref(0)
const todayReportCount = ref(0)
const warningCount = ref(0)
const dangerCount = ref(0)

// 设备列表
const deviceList = ref<DeviceVO[]>([])
const deviceLoading = ref(false)

// 最近报告数据
const latestReports = ref<any[]>([])
const latestReportsLoading = ref(false)

// 获取设备名称
const getDeviceName = (deviceId: string) => {
  const device = deviceList.value.find((item) => item.deviceId === deviceId)
  return device ? device.deviceName : deviceId
}

// 获取上报数据类型标签
const getReportTypeLabel = (type: string) => {
  return reportDataTypeOptions.find((item) => item.value === type)?.label || type
}

// 获取上报数据级别标签
const getReportLevelLabel = (level: string) => {
  return reportDataLevelOptions.find((item) => item.value === level)?.label || level
}

// 获取上报数据级别类型
const getReportLevelType = (level: string) => {
  return reportDataLevelOptions.find((item) => item.value === level)?.type || ''
}

// 加载设备列表
const loadDevices = async () => {
  deviceLoading.value = true
  try {
    const res = await DeviceApi.getDeviceList()
    deviceList.value = res || []
  } catch (error) {
    console.error('获取设备列表失败', error)
  } finally {
    deviceLoading.value = false
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    // 模拟加载统计数据，实际项目中应该调用后端API
    deviceCount.value = deviceList.value.length

    // 计算总能耗
    totalEnergy.value = deviceList.value.reduce((sum, device) => {
      return sum + (device.energyConsumption || 0)
    }, 0)

    // 其他统计数据，实际项目中应从后端获取
    todayReportCount.value = latestReports.value.length
    warningCount.value = latestReports.value.filter(
      (item) => item.reportDataLevel === 'warning'
    ).length
    dangerCount.value = latestReports.value.filter(
      (item) => item.reportDataLevel === 'danger'
    ).length
  } catch (error) {
    console.error('加载统计数据失败', error)
  }
}

// 加载最近报告数据
const loadLatestReports = async () => {
  latestReportsLoading.value = true
  try {
    const pageParams = {
      pageNo: 1,
      pageSize: 10
    }
    const res = await ReportApi.getReportDataPage(pageParams)
    if (res && res.list) {
      latestReports.value = res.list
    }
  } catch (error) {
    console.error('获取最近报告数据失败', error)
  } finally {
    latestReportsLoading.value = false
  }
}

// 刷新最近报告数据
const refreshLatestReports = async () => {
  await loadLatestReports()
  loadStatistics()
  ElMessage.success('数据已刷新')
}

// WebSocket服务地址
const wsUrl = computed(() => {
  return (
    (import.meta.env.VITE_BASE_URL + '/infra/ws').replace('http', 'ws') +
    '?token=' +
    getRefreshToken()
  )
})

// 初始化WebSocket连接
const ws = ref<WebSocket | null>(null)
const webSocketConnected = ref(false)

// 建立WebSocket连接
const connectWebSocket = () => {
  debugger
  try {
    if (
      ws.value &&
      (ws.value.readyState === WebSocket.OPEN || ws.value.readyState === WebSocket.CONNECTING)
    ) {
      console.log('WebSocket已连接或正在连接中')
      return
    }

    console.log('正在连接WebSocket:', wsUrl.value)
    ws.value = new WebSocket(wsUrl.value)

    ws.value.onopen = (event) => {
      console.log('WebSocket连接已打开:', event)
      webSocketConnected.value = true
      ElMessage.success('WebSocket连接已成功建立')
    }

    ws.value.onclose = (event) => {
      console.log('WebSocket连接已关闭, code:', event.code, 'reason:', event.reason, event)
      webSocketConnected.value = false

      // 显示连接关闭消息
      ElMessage.warning(`WebSocket连接已关闭: ${event.reason || '未知原因'}`)

      // 尝试重新连接
      setTimeout(connectWebSocket, 5000)
    }

    ws.value.onerror = (error) => {
      console.error('WebSocket连接出错:', error)
      webSocketConnected.value = false
      ElMessage.error('WebSocket连接出错，请查看控制台')
    }

    ws.value.onmessage = (event) => {
      console.log('WebSocket收到消息事件:', event)
      handleWebSocketMessage(event.data)
    }
  } catch (error) {
    console.error('初始化WebSocket连接时出错:', error)
    ElMessage.error('WebSocket连接初始化失败: ' + (error as Error).message)
  }
}

// 处理WebSocket消息
const handleWebSocketMessage = (messageData: string) => {
  console.log('收到WebSocket消息:', messageData)

  // 心跳消息处理
  if (messageData === 'pong') {
    console.log('收到心跳消息')
    return
  }

  try {
    // 解析消息
    const jsonMessage = JSON.parse(messageData)
    console.log('解析后的消息对象:', jsonMessage)

    // 获取消息类型
    const type = jsonMessage.type
    console.log('消息类型:', type)

    // 处理能源报告创建的消息类型
    if (type === 'energy-report-created') {
      console.log('收到能源报告创建消息')

      // 尝试多种方式解析内容
      let content: any = null

      try {
        // 尝试方式1: 作为JSON字符串解析
        if (typeof jsonMessage.content === 'string') {
          content = JSON.parse(jsonMessage.content)
          console.log('成功解析content为对象:', content)
        }
        // 尝试方式2: 内容已经是对象
        else if (typeof jsonMessage.content === 'object') {
          content = jsonMessage.content
          console.log('content已经是对象:', content)
        }
      } catch (e) {
        console.warn('解析content失败，使用原始内容:', e)
        content = jsonMessage.content
      }

      // 内容不存在则使用备用方案
      if (!content) {
        console.warn('无法获取消息内容，尝试使用整个消息对象')
        content = jsonMessage
      }

      console.log('最终使用的能源报告数据:', content)

      // 提取必要的字段，避免undefined错误
      const deviceId = content.deviceId || '未知设备'
      const reportDataType = content.reportDataType || '未知类型'
      const reportDataValue = content.reportDataValue || 0

      // 显示消息提示
      ElMessage({
        message: `新的能源报告数据已创建 - 设备ID: ${deviceId}, 数据类型: ${getReportTypeLabel(reportDataType) || reportDataType}, 数据值: ${reportDataValue}`,
        type: 'success',
        duration: 5000
      })

      // 刷新最近报告和统计数据
      refreshLatestReports()
    } else {
      console.log('收到其他类型消息:', type, jsonMessage)
    }
  } catch (error) {
    console.error('处理WebSocket消息失败:', error, '原始消息:', messageData)
    ElMessage.error('WebSocket消息处理出错，请查看控制台')
  }
}

// 关闭WebSocket连接
const closeWebSocket = () => {
  if (ws.value) {
    ws.value.close()
    ws.value = null
    webSocketConnected.value = false
    console.log('WebSocket连接已关闭')
  }
}

// 手动发送心跳
const sendPing = () => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.send('ping')
    console.log('发送心跳消息')
  }
}

// 心跳定时器
let heartbeatTimer: number | null = null

onMounted(async () => {
  // 加载初始数据
  await loadDevices()
  await loadLatestReports()
  loadStatistics()

  debugger
  // 连接WebSocket
  connectWebSocket()

  // 设置心跳
  heartbeatTimer = window.setInterval(() => {
    sendPing()
  }, 30000) // 30秒发送一次心跳
})

onBeforeUnmount(() => {
  // 清除心跳定时器
  if (heartbeatTimer) {
    clearInterval(heartbeatTimer)
  }

  // 关闭WebSocket连接
  closeWebSocket()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.energy-stats {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.stat-item {
  flex: 1;
  min-width: 110px;
  text-align: center;
  padding: 15px 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.connection-status {
  padding: 15px;
}
</style>
